package clone;


/*
* 2、深拷贝
* 深拷贝把要复制的对象所引用的对象都复制了一遍。
* */
public class CloneDemo1 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher1 teacher = new Teacher1();
        teacher.setName("lihua");
        teacher.setAge(28);

        Student1 student1 = new Student1();
        student1.setName("xiaoming");
        student1.setAge(18);
        student1.setTeacher(teacher);

        //拷贝一个student
        Student1 student2 = (Student1) student1.clone();
        System.out.println("-------------拷贝后-------------");
        System.out.println(student2.getName());
        System.out.println(student2.getAge());
        System.out.println(student2.getTeacher().getName());
        System.out.println(student2.getTeacher().getAge());

        System.out.println("-------------修改老师的信息后-------------");
        // 修改老师的信息
        teacher.setName("修改student1的teacher的name");
        System.out.println("student1的teacher为： " + student1.getTeacher().getName());
        System.out.println("student2的teacher为： " + student2.getTeacher().getName());

    }
}

class Student1 implements Cloneable{
    private String name;
    private int age;
    private Teacher1 teacher;

    public Student1() {
    }

    public Student1(String name, int age, Teacher1 teacher) {
        this.name = name;
        this.age = age;
        this.teacher = teacher;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Teacher1 getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher1 teacher) {
        this.teacher = teacher;
    }



    //clone()方法是Object提供的，它会返回一个指定的对象的副本
    @Override
    protected Object clone() throws CloneNotSupportedException {

        // return super.clone(); 浅拷贝
        //深拷贝
        //1、先获取这个对象的一个浅拷贝对象
        Student1 student1 = (Student1)super.clone();
        //2、将student1中所有的引用对象都获取一次
        student1.setTeacher((Teacher1) student1.getTeacher().clone());

        return student1;
    }

}

class Teacher1 implements Cloneable{
    private String name;
    private int age;

    public Teacher1() {
    }

    public Teacher1(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}